
$(document).ready(
	function () {
		$(".zipRequest").click(function() {
			zipRequest();
		});
	}
);

function zipRequest() {
	$("#zipExtension").unbind("click");
	$.getJSON(relativeContext + "catalog/zip/" + identifier, function(data){
		zipResponse(data);
	});
}

function zipProgress() {
	$.getJSON(relativeContext + "catalog/progress/" + identifier, function(data){
		zipResponse(data);
	});
}

function zipResponse(data) {
	if (data.completed) {
		$("#zipProgress").animate({width: "100%"}, 2000, function() {
			swapIcon(data.url);
		});
	} else {
		attachMeter("zip");
		var percent = Math.floor((data.progress / data.files) * 100);
		$("#zipProgress").animate({width: percent + "%"}, 2000, zipProgress);
	}
}

function swapIcon(url) {
	$("#zipIcon").remove();

	var link = document.createElement("a");
	var icon = document.createElement("img");

	$("#zipExtension").attr("class", "zipReady");

	$(icon).attr("id", "zipIcon");
	$(icon).attr("src", relativeContext + "images/zip.png");

	$(link).attr("href", url);
	$(link).attr("id", "zipLink");

	var zfn = $("#zipFilename");
	$(link).append(icon);
	$("#zipExtension").prepend(link);
	$(link).append(zfn);
	zfn.show();

	$("#zipMeter").remove();
}

function attachMeter(prefix) {
	var zm = $("#" + prefix + "Meter");

	if (zm.length == 0) {
		$("#zipFilename").hide();

		var meterContainer = document.createElement("div");
		var meterOuter = document.createElement("div");
		var meterInner = document.createElement("div");
	
		$(meterContainer).attr("class", "meterContainer");
		$(meterContainer).attr("id", prefix + "Meter");
		$(meterContainer).append(meterOuter);
		$(meterOuter).attr("class", "meterOuter");
		$(meterOuter).append(meterInner);
		$(meterInner).attr("class", "meterInner");
		$(meterInner).attr("id", prefix + "Progress");

		$("#" + prefix + "Icon").after(meterContainer);
	}
}